// 合同录入弹窗
<template>
    <div class="addDialog">
        <el-dialog  :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @closed="handleClosed">
            <el-form ref="form" :rules="rules" :model="operationContract">
                <el-row :gutter="40">
                    <el-col :span="8">
                        <el-form-item label="工程名称" class="listFormItem" prop="engineeringName">
                            <el-button class="add" type="primary" size="mini" @click="$refs.propertyChoose.show();" v-if="type === 'add'">选择</el-button>
                            <el-input v-model="operationContract.engineeringName" placeholder="请选择工程名称" readonly/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                       <el-form-item label="单位名称" class="full" prop="unitName">
                            <el-input v-model="operationContract.unitName" readonly placeholder="请输入单位名称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="物业名称" class="full" prop="propertyName">
                            <el-input v-model="operationContract.propertyName" readonly placeholder="请输入物业名称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" class="breakItem" prop="propertyName">
                            <el-select v-model="operationContract.businessType" placeholder="请选择">
                                <el-option label="工程施工合同" value="1">工程施工合同</el-option>
                                <el-option label="物业服务合同" value="2">物业服务合同</el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同编号" class="full" prop="code">
                            <el-input v-model="operationContract.contractNumber" maxlength="30" placeholder="请输入合同编号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="签订日期" prop="signTime">
                            <el-date-picker
                                v-model="operationContract.signTime"
                                type="datetime"
                                placeholder="请输入签订日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="合同金额" class="full" prop="totalAmount">
                            <el-input v-model="operationContract.totalAmount" oninput ="value=value.replace(/[^0-9.]/g,'')" maxlength="15" placeholder="请输入合同金额"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="工期" class="full" prop="constructionPeriod">
                            <el-input v-model.number="operationContract.constructionPeriod" maxlength="5" placeholder="请输入工期">
                                <i slot="suffix">天</i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="付款方式" class="full" prop="payMethod">
                            <el-input v-model="operationContract.payMethod" type="textarea" maxlength="64" placeholder="请输入付款方式"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" class="full" prop="remarks">
                            <el-input v-model="operationContract.remarks" type="textarea" maxlength="200" placeholder="请输入内容"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="服务价目列表" class="full" prop="operateContractDetailList">
                        <el-button size="mini" type="primary" style="float: right" @click="addDetailList">添加</el-button>
                        <el-table :data="operateContractDetailList" >
                            <el-table-column type="index" label="序号" width="50"/>
                            <el-table-column prop="unitPrice" label="单价(元/m²)" width="180">
                                <template slot-scope="scope">
                                    <el-input oninput ="value=value.replace(/[^0-9.]/g,'')" maxlength="12" v-model="scope.row.unitPrice" placeholder="单价(元/m²)" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="costItems" label="费用项目">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.costItems" maxlength="50" placeholder="项目名称"/>
                                </template>
                            </el-table-column>
                            <el-table-column prop="paymentAmount" label="付款金额(元)">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.paymentAmount" oninput ="value=value.replace(/[^0-9.]/g,'')" maxlength="15" placeholder="付款金额(元)"/>
                                </template>
                            </el-table-column>
                            <el-table-column prop="discountAmount" label="折扣金额(元)">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.discountAmount" oninput ="value=value.replace(/[^0-9.]/g,'')" maxlength="15" placeholder="折扣金额(元)"/>
                                </template>
                            </el-table-column>
                            <el-table-column prop="finallyAmount" label="最终金额(元)">
                                <template slot-scope="scope">
                                    <span>{{getTotalCount(scope.$index, scope.row.paymentAmount, scope.row.discountAmount)}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" v-if="type !== 'preview'">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="text" @click="releteDetailList(scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-row>
            </el-form>
            <!-- 工程选择弹窗 -->
            <propertyChooseDialog
                ref="propertyChoose"
                dialogType="contract"
                @changeProperty="handlePropertyChange"
            />
            <div slot="footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button  v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import uploadMedia from '@/components/upload-media';
import moment from 'moment';
import { changeContract, getContractById, getChoicedBudgetList } from "@/views/wy-operate/api/repair.js";
export default {
    name: 'addDepartment',
    inject: ['initList'],
    components: {
        propertyChooseDialog
    },
    data() {
        return {
            type: 'add',//弹窗类型，默认新增
            //弹窗开关
            dialogVisible: false,
            // 校验规则
            rules: {
                engineeringName:  [{required: true, message: '工程名称不能为空', trigger: 'blur'}],
                businessType:  [{required: true, message: '合同类型不能为空', trigger: 'blur'}],
                propertyName:  [{required: true, message: '物业名称不能为空', trigger: 'blur'}],
                unitName:  [{required: true, message: '单位名称不能为空', trigger: 'blur'}],
                signTime:  [{required: true, message: '签订日期不能为空', trigger: 'blur'}],
                totalAmount:  [
                    {required: true, message: '合同金额不能为空', trigger: 'blur'},
                    { pattern:  /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的金额", trigger: "blur" },
                ],
                constructionPeriod:  [
                    {required: true, message: '工期不能为空', trigger: 'blur'},
                    {type: 'number', min: 0,  message: '请输入正确工期（必须为数字且最小为0）', trigger: 'blur'}
                ],
                payMethod:  [{required: true, message: '付款方式不能为空', trigger: 'blur'}],
            },
            //合同基本信息
            operationContract:{
                contractId: '', //合同id
                supplierId:'',//供应商id
                businessType:'',//业务类型
                engineeringName:'',//工程名称
                roomId:'',//物业id
                propertyName:'',//物业名称
                area:'',//物业面积
                contractType:'',//合同类型
                contractSource:'',//合同来源
                signTime: '',//签订时间
                contractNumber:'',//合同编号
                contractName:'',//合同名称
                unitType:'',//单位类型
                unitName:'',//单位名称
                startTime:'',//开工时间
                endTime:'',//竣工时间
                constructionPeriod:'',//工期
                budgetAmount:'',//预算金额
                censorshipAmount:'',//送审金额
                approvalAmount:'',//审定金额
                contractAmount:'',//合同金额
                totalAmount:'',//总金额
                payMethod:'',//付款方式
                remarks:''//备注
            },
            //服务价目列表
            operateContractDetailList:[],
        }
    },
    computed: {
         // 弹窗标题计算
        dialogTitle() {
            return {
                'preview': '查看',
                'edit': '编辑',
                'add': '新增'
            }[this.type]
        },
	},
    methods: {
        //开启弹窗
        show({type, data = {}}) {
            if(['preview','edit'].includes(type)) {
                getContractById(data.contractId).then(res => {
                    const { operationContract, operateContractDetailList } = res.data.data
                    const { approvalAmount, censorshipAmount, censorshipDate, engineeringName, obtId, propertyName, reductionAmount, unitName, unitType } = operationContract
                    //合同基本信息
                    this.operationContract = operationContract;
                    //服务价目列表
                    this.operateContractDetailList = operateContractDetailList;
                });
            }
            this.type = type;
            this.dialogVisible = true;
        },
        // 提交新增
        save() {
            //this.dialogVisible = false
            if(['edit','add'].includes(this.type)) {
                this.$refs.form.validate((valid) => {
                   if (valid && this.customValidate()) {
                        const params = {
                            operationContract: this.operationContract,
                            operateContractDetailList: this.operateContractDetailList,
                            obtId: this.operationContract.obtId
                        }
                        changeContract(params, this.type).then(res => {
                            if (res.data.code == 0) {
                                this.$message.success(`${this.dialogTitle}成功!`);
                                this.initList({current: 1, queryString:'', businessType:''})
                                this.dialogVisible = false;
                            } else {
                                this.$message.error(res.data.code)
                            }
                        })
                    }
                });
            }

        },
        // 自定义表单验证
        customValidate(){
            if(this.operateContractDetailList.length) {
                if(this.operateContractDetailList.some(item => item.unitPrice == '')){
                    this.$message.error('单价不能为空')
                    return false
                } else if(this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.unitPrice))) {
                    this.$message.error('请输入正确的单价')
                    return false
                } else if(this.operateContractDetailList.some(item => item.costItems == '')){
                    this.$message.error('费用项目不能为空')
                    return false
                } else if(this.operateContractDetailList.some(item => item.paymentAmount == '')){
                    this.$message.error('付款金额不能为空')
                    return false
                } else if(this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.paymentAmount))){
                    this.$message.error('请输入正确的付款金额')
                    return false
                } else if(this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.discountAmount))){
                    this.$message.error('请输入正确的折扣金额')
                    return false
                }
            }
            return true
        },
        // 添加物业价目明细
        addDetailList(){
            this.operateContractDetailList.push({
                contractDetailId:'',//价目表id
                contractId:'',//合同id  后台已做统一赋值为合同基本信息表id
                unitPrice:'',//单价
                costItems:'',//费用项目
                paymentAmount:'',//付款金额
                discountAmount:'',//折扣金额
                finallyAmount: '',//最终金额
                remarks:'',//备注
            })
        },
        // 删除价目明细
        releteDetailList(index){
            this.operateContractDetailList.splice(index,1)
        },
        // 计算价格
        getTotalCount(index, paymentAmount = 0, discountAmount = 0) {
            let totalCount = 0;
            totalCount = (paymentAmount - discountAmount).toFixed(2)
            this.operateContractDetailList[index].finallyAmount = totalCount
            return totalCount
        },
        // 选择预算回调
        handlePropertyChange(data){
            this.operationContract = {
                ...this.operationContract,
                ...data
            }
        },
        //弹窗关闭监听
        handleClosed(){
            for(var i in this.operationContract) {
                this.operationContract[i] = ''
            }
            this.operateContractDetailList.length = 0
        },
    },
}
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
</style>
